
class GradeManager:
    def __init__(self):
        self.students = {}  # {student_id: {'name': name, 'grades': {course: score}}}
        self.courses = {}   # {course: {student_id: score}}

    def add_grade(self, name, student_id, course, score):
        # 数据验证
        if not (0 <= score <= 100):
            return "错误：成绩必须在0-100之间"
            
        if student_id in self.students:
            if course in self.students[student_id]['grades']:
                return "错误：该学生此课程成绩已存在"
        else:
            self.students[student_id] = {'name': name, 'grades': {}}
            
        self.students[student_id]['grades'][course] = score
        self.courses.setdefault(course, {})[student_id] = score
        return "成绩已成功记录！"

    def query_by_name(self, name):
        results = []
        for student_id, info in self.students.items():
            if info['name'] == name:
                for course, score in info['grades'].items():
                    results.append(f"姓名：{name}, 学号：{student_id}, 课程：{course}, 成绩：{score}")
        return results if results else ["未找到相关记录。"]

    def query_by_id(self, student_id):
        if student_id in self.students:
            results = []
            for course, score in self.students[student_id]['grades'].items():
                results.append(f"姓名：{self.students[student_id]['name']}, 学号：{student_id}, 课程：{course}, 成绩：{score}")
            return results
        return ["未找到相关记录。"]

    def query_by_course(self, course):
        if course in self.courses:
            results = []
            for student_id, score in self.courses[course].items():
                results.append(f"姓名：{self.students[student_id]['name']}, 学号：{student_id}, 课程：{course}, 成绩：{score}")
            return results
        return ["未找到相关记录。"]

    def course_statistics(self, course):
        if course not in self.courses or not self.courses[course]:
            return ["该课程暂无成绩记录。"]
            
        scores = list(self.courses[course].values())
        avg = sum(scores) / len(scores)
        return [
            f"课程：{course}",
            f"平均分：{avg:.2f}",
            f"最高分：{max(scores)}",
            f"最低分：{min(scores)}"
        ]

def display_menu():
    print("""
=================================
欢迎使用学生成绩管理系统
=================================
请选择操作：
1. 记录学生成绩
2. 查询学生成绩
3. 统计课程成绩
4. 退出系统
    """)

def main():
    manager = GradeManager()
    
    while True:
        display_menu()
        choice = input("请输入选项序号：")
        
        if choice == '1':
            print("\n===== 记录学生成绩 =====")
            name = input("请输入学生姓名：")
            student_id = input("请输入学生学号：")
            course = input("请输入课程名称：")
            try:
                score = float(input("请输入成绩（0-100）："))
                result = manager.add_grade(name, student_id, course, score)
                print(result)
            except ValueError:
                print("错误：请输入有效的数字成绩")
                
        elif choice == '2':
            print("\n===== 查询学生成绩 =====")
            print("请选择查询方式：")
            print("1. 按学生姓名查询")
            print("2. 按学生学号查询")
            print("3. 按课程名称查询")
            query_choice = input("请输入选项序号：")
            
            if query_choice == '1':
                name = input("请输入学生姓名：")
                results = manager.query_by_name(name)
            elif query_choice == '2':
                student_id = input("请输入学生学号：")
                results = manager.query_by_id(student_id)
            elif query_choice == '3':
                course = input("请输入课程名称：")
                results = manager.query_by_course(course)
            else:
                print("错误：无效的查询选项")
                continue
                
            for result in results:
                print(result)
                
        elif choice == '3':
            print("\n===== 统计课程成绩 =====")
            course = input("请输入课程名称：")
            results = manager.course_statistics(course)
            for result in results:
                print(result)
                
        elif choice == '4':
            print("感谢使用学生成绩管理系统，再见！")
            break
            
        else:
            print("错误：无效的选项，请输入1-4之间的数字")
            
        input("\n按回车键继续...")

if __name__ == "__main__":
    main()
#